//注册路由的插件
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import fs from 'fs'
import path from 'path'

export  function registerRouter(app) {
    let router = new Router()
    app.use(bodyParser())
    let HeadPath = path.join(path.resolve('.'),'./controllers')
    let filePath = fs.readdirSync(HeadPath).filter(item => item.endsWith('.js')).map(item =>path.join('file:///',HeadPath,item))
    function RegisterRouter(filePath) {
        filePath.forEach(async item => {
            let { obj } = await import(item)
            for(let item in obj){
                let [method,path] = item.split(' ')
                let fn = obj[item]
                if(method === 'get') router.get(path,fn)
                if(method === 'post') router.post(path,fn)
                if(method === 'put') router.put(path,fn)
                if(method === 'delete') router.delete(path,fn)
            }
        })
    }
    
    RegisterRouter(filePath)

    return router.routes()
}